package com.leyou.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @version V1.0
 * @author: Ljxpa
 * @date: 2020/03/03 19:09
 * @description: 配置类，创建一个CorsFilter对象交给spring
 */
@Configuration
@EnableConfigurationProperties(CorsFilterConfigProperties.class)
public class CorsFilterConfiguration {
	@Bean
	public CorsFilter corsFilter(CorsFilterConfigProperties properties) {
		//创建cors配置类
		CorsConfiguration config = new CorsConfiguration();
		//添加所有允许的源信息
		properties.getAllowedOrigins().forEach(config::addAllowedOrigin);
		//设置是否允许跨域使用Cookie信息
		config.setAllowCredentials(properties.getAllowCredentials());
		//设置允许的请求方式
		properties.getAllowedMethods().forEach((method) -> {
			config.addAllowedMethod(method);
		});
		//设置允许的头信息
		properties.getAllowedHeaders().forEach((header) -> {
			config.addAllowedHeader(header);
		});
		//设置option预检请求的有效期
		config.setMaxAge(properties.getMaxAge());

		//添加映射路径，这里配置拦截一切请求
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration(properties.getFilterPath(), config);

		//创建一个CorsFilter对象并返回
		return new CorsFilter(source);
	}
}
